﻿using SmartParkingClient.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SmartParkingClient.DAL
{
    /// <summary>
    /// 主要处理   请求WebApi的过程
    /// </summary>
    public class WebDataAccess : IWebDataAccess
    {
        readonly string baseUrl = "http://localhost:5000/";
        
        #region Post方式进行请求
        /// <summary>
        /// 这个Form表单的形式
        /// </summary>
        /// <param name="url">请求的URL地址</param>
        /// <param name="content">表单数据</param>
        /// <returns></returns>
        public async Task<string> PostDatas(string url, HttpContent content)
        {
            using (var client = new HttpClient())// Http   Header   Body
            {
                client.BaseAddress = new Uri(baseUrl);
                //client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "Token");//认证
                var resp = await client.PostAsync(url, content);
                //resp.IsSuccessStatusCode
                return await resp.Content.ReadAsStringAsync();
            }
        }

        // 字符串
        // 文件二进制
        public MultipartFormDataContent GetFormData(Dictionary<string, HttpContent> contents)
        {
            var postContent = new MultipartFormDataContent();
            string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));

            postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");

            // "{\"username\":\"admin\",\"password\":\"123456\"}"

            foreach (var item in contents)
            {
                // 需要进行传递的键值对：比如 ：username=admin
                postContent.Add(item.Value, item.Key);
            }

            return postContent;
        }
        #endregion

        // Get方式进行请求

        public async Task<string> GetDatas(string url)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);
                var resp = await client.GetAsync(url);
                return await resp.Content.ReadAsStringAsync();
            }
        }
    }
}
